package com.jxzyk.util;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;

import com.core.util.ACache;
import com.core.util.Sharepf;
import com.jxzyk.entity.User;

public class UserManger {
	private Context ctx;
	private ACache aCache;
	public static String KEY_USER = "key_user";
	public static String KEY_AUTO = "key_auto";
	public static String KEY_SAVE = "key_save";
	public static String KEY_USER_NAME = "key_user_name";

	public UserManger(Context ctx) {
		this.ctx = ctx;
		aCache = ACache.get(ctx);
	}

	public String getUserName() {
		return (String) Sharepf.get(KEY_USER_NAME, "");
	}

	public void setUserName(String userName) {
		Sharepf.put(KEY_USER_NAME, userName);
	}

	public void setSave(boolean open) {
		Sharepf.put(KEY_SAVE, open);
	}

	public boolean getSave() {
		return (Boolean) Sharepf.get(KEY_SAVE, false);
	}

	public void setAuto(boolean open) {
		Sharepf.put(KEY_AUTO, open);
	}

	public boolean getAuto() {
		return (Boolean) Sharepf.get(KEY_AUTO, false);
	}

	public void saveUser(String json) throws JSONException {
		JSONObject jObject = new JSONObject(json);
		JSONArray array = jObject.getJSONArray("data");
		if (array.length() == 1) {
			jObject = array.getJSONObject(0);
			// aCache.put(KEY_USER, jObject, ACache.TIME_DAY);// 存放一天
			aCache.put(KEY_USER, jObject);
		}
	}

	public User getUser() throws Exception {
		User user = null;
		JSONObject json = aCache.getAsJSONObject(KEY_USER);
		if (json != null) {
			String jsonString = json.toString();
			user = (User) new User().instance(new com.alibaba.fastjson.JSONObject().parseObject(jsonString));
		}
		return user;
	}

	public void updateUser(User user) throws JSONException {
		JSONObject jObject = new JSONObject(user.toJsonString());
		aCache.put(KEY_USER, jObject);
	}
}
